{{define "system/logs.html"}}
{{template "layouts/base.html" .}}
{{end}}

{{define "content"}}
<div x-data="logsManager()" x-init="init()">
    <!-- 错误提示 -->
    <div x-show="showErrorMessage" x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0 transform translate-y-2" x-transition:enter-end="opacity-100 transform translate-y-0" x-transition:leave="transition ease-in duration-200" x-transition:leave-start="opacity-100 transform translate-y-0" x-transition:leave-end="opacity-0 transform translate-y-2" class="fixed top-4 right-4 z-50">
        <div class="bg-red-50 border border-red-200 rounded-md p-4 shadow-lg max-w-md">
            <div class="flex">
                <div class="flex-shrink-0">
                    <svg class="w-5 h-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium text-red-800" x-text="error"></p>
                </div>
                <div class="ml-auto pl-3">
                    <div class="-mx-1.5 -my-1.5">
                        <button @click="hideError()" class="inline-flex bg-red-50 rounded-md p-1.5 text-red-500 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-red-50 focus:ring-red-600">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 页面标题 -->  
    <div class="mb-6">
        <h1 class="text-2xl font-semibold text-gray-900">系统日志</h1>
        <p class="mt-1 text-sm text-gray-600">查看系统操作日志和审计记录</p>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">用户ID</label>
                <input type="text" x-model="filters.userId" placeholder="输入用户ID" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">操作类型</label>
                <input type="text" x-model="filters.action" placeholder="输入操作类型" 
                       class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">资源类型</label>
                <select x-model="filters.resource" 
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">全部资源</option>
                    <option value="user">用户</option>
                    <option value="role">角色</option>
                    <option value="permission">权限</option>
                    <option value="customer">客户</option>
                    <option value="partner">合作机构</option>
                    <option value="push">推送</option>
                </select>
            </div>
            <div class="flex items-end">
                <button @click="searchLogs()" :disabled="loading"
                        class="w-full bg-blue-600 text-white p-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed" title="搜索">
                    <template x-if="loading">
                        <div class="flex items-center justify-center">
                            <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                        </div>
                    </template>
                    <template x-if="!loading">
                        <div class="flex items-center justify-center">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                            </svg>
                        </div>
                    </template>
                </button>
            </div>
        </div>
    </div>

    <!-- 日志列表 -->
    <div class="bg-white rounded-lg shadow-sm">

                
        <!-- 批量操作栏 -->
        <div x-show="selectedLogs.length > 0" class="bg-blue-50 border-b border-blue-200 px-6 py-3">
            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <span class="text-sm text-blue-700">已选择 <span x-text="selectedLogs.length"></span> 条日志</span>
                </div>
                <div class="flex space-x-2">
                    <button @click="batchExportLogs()" class="bg-green-600 text-white px-3 py-1 rounded text-sm hover:bg-green-700">
                        批量导出
                    </button>
                    <button @click="batchDeleteLogs()" class="bg-red-600 text-white px-3 py-1 rounded text-sm hover:bg-red-700">
                        批量删除
                    </button>
                    <button @click="selectedLogs = []" class="bg-gray-600 text-white px-3 py-1 rounded text-sm hover:bg-gray-700">
                        取消选择
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 表格头部 -->
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
                <h3 class="text-lg font-medium text-gray-900">操作日志</h3>
                <div class="text-sm text-gray-500">
                    共 <span x-text="pagination.total"></span> 个日志
                </div>
            </div>
        </div>
        
        <div class="overflow-x-auto">
            <!-- Loading 状态 -->
            <div x-show="loading" class="flex justify-center items-center py-12">
                <div class="text-center">
                    <svg class="animate-spin w-10 h-10 text-blue-500 mb-4 mx-auto" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p class="text-gray-600">加载中...</p>
                </div>
            </div>
            
            <!-- 数据表格 -->
            <table x-show="!loading" class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" @change="toggleSelectAll()" :checked="isAllSelected()" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            时间
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            用户
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            操作
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            资源
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            IP地址
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                            详情
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <template x-for="log in logs" :key="log.id">
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <input type="checkbox" :value="log.id" x-model="selectedLogs" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="formatDateTime(log.created_at)"></td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm font-medium text-gray-900" x-text="log.user ? log.user.real_name : '系统'"></div>
                                <div class="text-sm text-gray-500" x-text="log.user ? log.user.username : '-'"></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full"
                                      :class="getActionClass(log.action)" x-text="log.action"></span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="log.resource"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500" x-text="log.ip_address"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500" x-text="log.details || '-'"></td>
                        </tr>
                    </template>
                    <!-- 无数据提示 -->
                    <tr x-show="!loading && logs.length === 0">
                        <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                            <div class="flex flex-col items-center">
                                <svg class="w-16 h-16 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
                                </svg>
                                <p class="text-lg font-medium">暂无日志数据</p>
                                <p class="text-sm">请尝试调整筛选条件</p>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        <div class="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6" x-show="!loading && pagination.total > 0">
            <div class="flex-1 flex justify-between sm:hidden">
                <button @click="prevPage()" :disabled="loading || pagination.page <= 1"
                        class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    上一页
                </button>
                <button @click="nextPage()" :disabled="loading || pagination.page >= Math.ceil(pagination.total / pagination.size)"
                        class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                    下一页
                </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示第 <span class="font-medium" x-text="(pagination.page - 1) * pagination.size + 1"></span> 到 
                        <span class="font-medium" x-text="Math.min(pagination.page * pagination.size, pagination.total)"></span> 条，
                        共 <span class="font-medium" x-text="pagination.total"></span> 条记录
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
                        <button @click="prevPage()" :disabled="loading || pagination.page <= 1"
                                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                     <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                                 </svg>
                        </button>
                        <button @click="nextPage()" :disabled="loading || pagination.page >= Math.ceil(pagination.total / pagination.size)"
                                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                     <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                                 </svg>
                        </button>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function logsManager() {
    return {
        logs: [],
        selectedLogs: [],
        filters: {
            userId: '',
            action: '',
            resource: ''
        },
        pagination: {
            page: 1,
            size: 20,
            total: 0
        },
        loading: false,
        error: '',
        showErrorMessage: false,
        initialized: false,
        searchTimer: null,

        async init() {
            if (this.initialized || this.loading) {
                return;
            }
            this.loading = true;
            this.initialized = true;
            
            try {
                await this.loadLogs();
            } catch (error) {
                console.error('初始化失败:', error);
                this.showError('初始化失败，请刷新页面重试');
            } finally {
                this.loading = false;
            }
        },

        showError(message) {
            this.error = message;
            this.showErrorMessage = true;
            // 3秒后自动隐藏错误提示
            setTimeout(() => {
                this.showErrorMessage = false;
            }, 3000);
        },

        hideError() {
            this.showErrorMessage = false;
        },

        async loadLogs() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    page: this.pagination.page,
                    size: this.pagination.size,
                    ...this.filters
                });
                
                const response = await fetch(`/api/v1/system/logs?${params}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    this.logs = data.data.logs || [];
                    this.pagination.total = data.data.total || 0;
                    this.pagination.page = data.data.page || 1;
                    this.pagination.size = data.data.size || 20;
                } else {
                    console.error('加载日志失败:', data.message);
                    // 显示错误提示
                    this.showError('加载日志失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('加载日志失败:', error);
                this.showError('网络错误，请检查网络连接后重试');
            } finally {
                this.loading = false;
            }
        },

        async searchLogs() {
            if (this.searchTimer) {
                clearTimeout(this.searchTimer);
            }
            this.searchTimer = setTimeout(async () => {
                this.pagination.page = 1;
                await this.loadLogs();
            }, 300);
        },

        async prevPage() {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                await this.loadLogs();
            }
        },

        async nextPage() {
            const maxPage = Math.ceil(this.pagination.total / this.pagination.size);
            if (this.pagination.page < maxPage) {
                this.pagination.page++;
                await this.loadLogs();
            }
        },

        formatDateTime(dateTime) {
            if (!dateTime) return '-';
            return new Date(dateTime).toLocaleString('zh-CN');
        },

        getActionClass(action) {
            const actionClasses = {
                'create': 'bg-green-100 text-green-800',
                'update': 'bg-blue-100 text-blue-800', 
                'delete': 'bg-red-100 text-red-800',
                'login': 'bg-purple-100 text-purple-800',
                'logout': 'bg-gray-100 text-gray-800'
            };
            return actionClasses[action] || 'bg-gray-100 text-gray-800';
        },

        // 全选/取消全选
        toggleSelectAll() {
            if (this.isAllSelected()) {
                this.selectedLogs = [];
            } else {
                this.selectedLogs = this.logs.map(log => log.id);
            }
        },

        // 检查是否全选
        isAllSelected() {
            return this.logs.length > 0 && this.selectedLogs.length === this.logs.length;
        }
    }
}
</script>
{{end}}